package com.ll.cpu;

/**
 * @author 刘龙
 * @version 1.0
 * 通过实现接口Runnable
 */
public class Thread02 {
    public static void main(String[] args) {
/*        Dog dog = new Dog();
        // 创建了Thread, 把dog对象(实现Runnable), 放入Thread
        // 这里底层使用了设计模式(静态代理)
        Thread thread = new Thread(dog);
        thread.start();*/

        Tiger tiger = new Tiger();
        ThreadProxy threadProxy = new ThreadProxy(tiger);
        threadProxy.start();

    }
}

class Animal{}

class Tiger extends Animal implements Runnable{

    @Override
    public void run() {
        System.out.println("老虎嗷嗷叫...");
    }
}

/**
 * 线程代理类, 模拟一个极简的Thread
 * 这里可以把Proxy类 当做 ThreadProxy
 */
class ThreadProxy implements Runnable {
    /**
     * 属性,类型是Runnable
     */
    private Runnable target = null;

    @Override
    public void run() {
        if (target != null) {
            // 动态绑定
            target.run();
        }
    }

    public ThreadProxy(Runnable target) {
        this.target = target;
    }

    public void start() {
        // 这个方法是真正实现多线程的方法
        start0();
    }

    public void start0() {
        run();
    }
}

/**
 * 通过实现接口Runnable,开发线程
 */
class Dog implements Runnable{
    private int count;
    @Override
    public void run() {
        while (true) {
            System.out.println("小狗汪汪叫" + (++count) + ",线程名: " + Thread.currentThread().getName());

            // 休眠1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 退出条件
            if (count == 10) {
                break;
            }
        }
    }
}


